package edu.dlust.trading_platform;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.dlust.trading_platform.DataBase.MySQL;
import edu.dlust.trading_platform.DataBase.UserSQLite;
import edu.dlust.trading_platform.DataBean.userdata;

public class LoginActivity extends AppCompatActivity {
    private EditText username, password;
    private CheckBox rpc;
    private Button login, register;
    private ImageView phone, mail;
    private UserSQLite userSQLite;
    private TextView change;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = findViewById(R.id.usernameEditText);
        password = findViewById(R.id.passwordEditText);
        rpc = findViewById(R.id.rememberPasswordCheckBox);
        userSQLite = new UserSQLite(this);
        Cursor cursor = userSQLite.getUser();
        if(cursor.getCount() != 0){
            while (cursor.moveToNext()){
                username.setText(cursor.getString(1));
                password.setText(cursor.getString(2));
            }
            rpc.setChecked(true);
        }
        cursor.close();
        login();
        other();
    }

    private void login() {
        username = findViewById(R.id.usernameEditText);
        password = findViewById(R.id.passwordEditText);
        rpc = findViewById(R.id.rememberPasswordCheckBox);
        login = findViewById(R.id.loginButton);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uname = username.getText().toString();
                String passwd = password.getText().toString();
                if (uname.equals("") || passwd.equals("")) {
                    Toast.makeText(LoginActivity.this, "请完整填写用户名或密码", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String strsql = "SELECT Pswd,UName,Image FROM LOGINID WHERE Uid = ?";
                            try {
                                Connection con = MySQL.getConnection();
                                if (con != null) {
                                    PreparedStatement ps = con.prepareStatement(strsql);
                                    ps.setString(1, uname);
                                    ResultSet rs = ps.executeQuery();
                                    if (rs.next()) {
                                        String pswd = rs.getString("Pswd");
                                        String Uname = rs.getString("UName");
                                        byte[] image = rs.getBytes("Image");
                                        if (passwd.equals(pswd)) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                            if(rpc.isChecked()){
                                                if (userSQLite.getUser().getCount() != 0) {
                                                    userSQLite.deleteUser();
                                                }
                                                userSQLite.addUser(uname,passwd);

                                                userdata.setUid(uname);
                                                userdata.setName(Uname);
                                                if (image != null) {
                                                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
                                                    userdata.setImg(bitmap);
                                                }else {
                                                    userdata.setImg(null);
                                                }

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Intent intent = new Intent(LoginActivity.this,HomePageActivity.class);
                                                        startActivity(intent);
                                                        LoginActivity.this.finish();
                                                    }
                                                });
                                            }else {
                                                userSQLite.deleteUser();

                                                userdata.setUid(uname);
                                                userdata.setName(Uname);
                                                if (image != null) {
                                                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
                                                    userdata.setImg(bitmap);
                                                }else {
                                                    userdata.setImg(null);
                                                }

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Intent intent = new Intent(LoginActivity.this,HomePageActivity.class);
                                                        startActivity(intent);
                                                        LoginActivity.this.finish();
                                                    }
                                                });
                                            }
                                        } else {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(LoginActivity.this, "密码错误！", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(LoginActivity.this, "账号不存在！", Toast.LENGTH_SHORT).show();
                                            }
                                        });
                                    }
                                    con.close();
                                } else {
                                    Log.e("LoginActivity", "Failed to establish database connection");
                                }
                            } catch (SQLException throwables) {
                                Log.e("LoginActivity", "SQL Exception: " + throwables.getMessage());
                                throwables.printStackTrace();
                            }
                        }
                    }).start();
                }
            }
        });
    }
    private void other(){
        register = findViewById(R.id.registerButton);
        phone = findViewById(R.id.imageView_phone);
        password = findViewById(R.id.passwordEditText);
        rpc = findViewById(R.id.rememberPasswordCheckBox);
        mail = findViewById(R.id.imageView_mail);
        username = findViewById(R.id.usernameEditText);
        change = findViewById(R.id.forgetPasswordTextView);
        ActivityResultLauncher launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        Intent data = result.getData();
                        if (data != null) {
                            String uid = data.getStringExtra("uid");
                            if (uid != null) {
                                username.setText(uid);
                                password.setText("");
                                rpc.setChecked(false);
                            }
                        } else {
                        }
                    }
                });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                launcher.launch(intent);
            }
        });
        phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this,PhoneLoginActivity.class);
                startActivity(intent);
            }
        });
        mail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this,QQLoginActivity.class);
                startActivity(intent);
                LoginActivity.this.finish();
            }
        });
        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this,ForgetPasswordActivity.class);
                startActivity(intent);
            }
        });
    }
}